package com.mcb_wxc.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by 小生
 * 2019/1/10 14:21.
 */
public class ParentValToSubclass {
    public static void main(String[] args) throws Exception {
        /*TProject tProject=new TProject();
        Project project=new Project();
        tProject.setAreaId(1);
        tProject.setAvgPrice("1000000");
        fatherToChild(tProject,project);
        System.out.println(project.getAreaId());*/
    }


    /**
     * 父类的值赋值到子类
     * @param father 父类
     * @param child 子类
     * @param <T>
     * @throws Exception
     */
    public static <T>void fatherToChild(T father,T child) throws Exception {
        if(father == null) {
            return;
        }
        if (child.getClass().getSuperclass()!=father.getClass()){
            throw new Exception(father.getClass().getName()+"child 不是 "+ child.getClass().getName() +" 的父类");
        }
        Class<?> fatherClass = father.getClass();
        Field[] declaredFields = fatherClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field=declaredFields[i];
            Method method=fatherClass.getDeclaredMethod("get"+upperHeadChar(field.getName()));
            Object obj = method.invoke(father);
            field.setAccessible(true);
            field.set(child,obj);
        }

    }

    /**
     * 首字母大写
     */
    public static String upperHeadChar(String in) {
        String head = in.substring(0, 1);
        String out = head.toUpperCase() + in.substring(1, in.length());
        return out;
    }
}
